<template>
	<view>
		<view class="">
			<!-- 导航栏  -->
			<topbar>
				<view class="ml36 mr40 ms22">
					<view class="flex-align">
						<view class="message mr30">信息</view>
						<view class="contactMen mr30 " @click="$pub.go('/pages_friend/contactMen/contactMen')">联系人</view>
						<!-- <view class=""><image src="/static/img/message/145.png" mode="" style="width: 31rpx;height: 31rpx;"></image></view> -->
					</view>
				</view>
			</topbar>

			<!-- 挤压层 -->
			<view class="" :style="{ 'padding-top': h + 'px' }"></view>

			<!-- <button @click="quitSocket">111</button> -->

			<!-- 群组 -->
			<view class="">
				<scroll-view class="scroll-view_H" scroll-x="true" @scroll="scroll" scroll-left="0">
					<view class="scroll-view-item_H uni-bg-red" v-for="(item, index) in circleList" :key="index" @click="goGroup(item)">
						<view class="flex">
							<view class="flex-cen ml16 mr6"><u-avatar :src="item.uavatar || src" size="25"></u-avatar></view>
							<view class="mr8">
								<view class=" color_fff">{{ item.uname }} {{ item.ucurrentSize }}人</view>
							</view>
							<view class=""><image src="/static/img/message/54901.svg" mode="" style="width: 31rpx;height: 31rpx;"></image></view>
						</view>
					</view>
				</scroll-view>
			</view>

			<u-empty v-if="friendList.length === 0" mode="message" icon=""></u-empty>

			<!-- 聊天信息 -->
			<view class="ms74">
				<!--  -->
				<view class="item ml36 mr46 mt40" v-for="item in friendList" :key="item" @click="goSolaChat(item)">
					<view class="flex-around">
						<view class="mr26"><image :src="item.uavatar" style="width: 100rpx;height: 100rpx;"></image></view>
						<view class="">
							<view class="flex-column">
								<view class="myFamily">{{ item.uremark }}</view>
								<view class="myMessage">{{ latestMessage[item.ufriendId].content || '暂无消息' }}</view>
								<!-- <view class="myMessage">{{ messageList[messageList.length - 1].content || '暂无消息' }}</view> -->
								<!-- <view class="myMessage">{{ talkList[talkList.length - 1].content || '暂无消息' }}</view> -->
								<!-- 								<view class="myMessage" v-for="(m, index) in talkList" :key="m.id">
									<view class="" v-if="item.ufriendId === m.from">{{ talkList[talkList.length - 1].content || '暂无消息' }}</view>
								</view> -->
								<view class="myTime ms18">2 min</view>
							</view>
						</view>
						<view class="">
							<view class="flex-cen" style="width: 48rpx;height: 48rpx;background-color: #A14BFF;border-radius: 50%;">
								<view class="" style="color: #FFFFFF;font-size: 22rpx;">{{ talkList.length }}</view>
							</view>
						</view>
					</view>
					<view
						class=""
						style="width: 750rpx;
							height: 0rpx;
							opacity: 0.24;
							border: 2rpx solid #CFD4DC;
					"
					></view>
				</view>
				<!--  -->
				<view class="item ml36 mr46 mt40" v-for="item in 9" :key="item" @click="$pub.go('/pages_friend/soloChat/soloChat')" style="display: none;">
					<view class="flex-around">
						<view class="mr26"><image src="/static/img/message/user.png" style="width: 100rpx;height: 100rpx;"></image></view>
						<view class="">
							<view class="flex-column">
								<view class="myFamily">兄弟群</view>
								<view class="myMessage">刘晓婷：看看孩子到家没，我准备下班了</view>
								<view class="myTime ms18">2 min</view>
							</view>
						</view>
						<view class="">
							<view class="" style="position: relative;">
								<image src="/static/img/message/msg.png" style="width: 48rpx;height: 48rpx;"></image>
								<view class="" style="top: 4rpx;left: 16rpx;position: absolute;color: #FFFFFF;">1</view>
							</view>
						</view>
					</view>
					<view
						class=""
						style="width: 750rpx;
					height: 0rpx;
					opacity: 0.24;
					border: 2rpx solid #CFD4DC;
					"
					></view>
				</view>
				<!--  -->
			</view>

			<!-- 底部 -->
			<tabbar></tabbar>
		</view>
	</view>
</template>

<script>
import {
	mapState, //先导入mapState方法
	mapMutations
} from 'vuex';
export default {
	data() {
		return {
			src: 'https://cdn.uviewui.com/uview/album/1.jpg',
			value6: 0,
			keyword: '',
			/* 下拉 */
			show: false,
			h: 0,
			scrollTop: 0,
			old: {
				scrollTop: 0
			},
			/*  */
			circleList: [],
			friendList: [],
			/*  */
			WebSocket: {},
			isSuccess: false,
			sendMessage: {},
			messList: [],

			/* websocket */
			/* websock */
			isSuccess: false,
			timer: '',
			isClose: false,
			sendMessage: {},
			talkList: [],
			socketTask: null,
			a: 1,
			connectNum: 1,
			/* 更新数据定时器 */
			setTimer: ''
		};
	},
	computed: {
		...mapState('websocket', ['messageList', 'historyList']),
		newFriendMessage() {
			var arr = [];
			console.log('sucesss');
			return;
			this.messageList.forEach(i => {
				for (var f = 0; f < this.friendList.length; f++) {
					if (i.fromId === f.ufriendId) {
						console.log(i.content, 'i.content');
						arr.push(i.content);
					}
				}
			});
			return arr;
		},
		latestMessage: {
			// getter
			get() {
				return {};
			},
			// setter
			set(newValue) {
				console.log(newValue, 'newValue');
			}
		}
	},
	onShow() {
		let that = this;
		this.h = getApp().globalData.systemHeight;
		//获取群和好友列表
		this.getCircleList();
		this.getFriendList();

		/* 初始化websocket */
		this.connectSocket();
		console.log(this.socketTask, 'this.socketTask');

		/* 更新消息 */
		try {
			this.setTimer = setInterval(() => {
				let userInfo = uni.getStorageSync('userInfo');
				let histroy = {
					cmd: 19,
					fromUserId: this.friendList,
					userId: String(userInfo.userId),
					type: 1
				};
				if (!that.isSuccess) return;
				this.friendList.forEach(i => {
					this.sendSocketMessage(
						JSON.stringify({
							cmd: 19,
							fromUserId: i.ufriendId,
							userId: String(userInfo.userId),
							// type: 1,
							type: 0,
							count: 10
						})
					);
				});
				// this.getMessage();
			}, 10000);
		} catch (e) {
			clearInterval(this.setTimer);
			console.log(e, 'e');
		}

		// this.changeA();
	},
	// 监听页面卸载
	onHide() {
		let that = this;
		console.log('des');
		that.socketTask.close();
		clearInterval(that.timer);
		clearInterval(this.setTimer);
	},
	methods: {
		changeA() {
			setInterval(() => {
				this.a++;
			}, 1000);
		},
		goGroup(data) {
			uni.navigateTo({
				url: `/pages_friend/groupChat/groupChat?data=${JSON.stringify(data)}`
			});
		},

		goSolaChat(data) {
			uni.navigateTo({
				url: `/pages_friend/soloChat/soloChat?data=${JSON.stringify(data)}`
			});
		},

		async getCircleList() {
			let re = await this.$API.usertoGroupApi.findUserGroupList();
			this.circleList = re;
		},
		async getFriendList() {
			let re = await this.$API.friendApi.findFriendList();
			this.friendList = re;
		},
		scroll: function(e) {
			console.log(e);
			this.old.scrollTop = e.detail.scrollTop;
		},
		/* long类型时间 */
		getTime() {
			var nowDate = new Date();
			var year = nowDate.getFullYear();
			var month = nowDate.getMonth();
			var today = nowDate.getDate();
			var hours = nowDate.getHours();
			var minutes = nowDate.getMinutes();
			var seconds = nowDate.getSeconds();

			if (month >= 1 && month <= 9) {
				month = '0' + month;
			}
			if (today >= 1 && today <= 9) {
				today = '0' + today;
			}
			var currentdate = year + '-' + month + '-' + today + ' ' + hours + ':' + minutes + ':' + seconds;
			console.log(currentdate);
			var currentDateLong = new Date(currentdate.replace(new RegExp('-', 'gm'), '/')).getTime();
			return currentDateLong;
		},

		async getMessage() {
			console.log('消息获取');
			let userInfo = uni.getStorageSync('userInfo');
			// {
			// 	from: '来源ID',
			// 	to: '目标ID',
			// 	cmd: '命令码(11)int类型',
			// 	createTime: '消息创建时间long类型',
			// 	msgType: '消息类型int类型(0:text、1:image、2:voice、3:vedio、4:music、5:news)',
			// 	chatType: '聊天类型int类型(0:未知,1:公聊,2:私聊)',
			// 	groupId: '群组id仅在chatType为(1)时需要,String类型',
			// 	content: '内容',
			// 	extras: "扩展字段,JSON对象格式如：{'扩展字段名称':'扩展字段value'}"
			// }

			// let fId = this.friendList[0]?.ufriendId;
			// console.log(fId);
			// console.log(this.friendList[0], 'this.friendList[0]');
			// console.log(this.friendList[0]?.ufriendId, 'this.friendList[0]?.ufriendId');
			// this.sendMessage = {
			// 	from: String(this.friendList[0]?.ufriendId),
			// 	to: String(userInfo.userId),
			// 	cmd: 11,
			// 	msgType: 0,
			// 	chatType: 2
			// };
			let friendList = this.friendList;
			console.log(friendList, 'friendList');
			console.log(this.sendMessage, 'this.sendMessage');
			for (var i = 0; i < friendList.length; i++) {
				this.sendMessage = {
					from: String(friendList[i]?.ufriendId),
					to: String(userInfo.userId),
					cmd: 11,
					msgType: 0,
					chatType: 2
				};
				// let socketRe = await this.$store.dispatch('websocket/WEBSOCKET_SEND', JSON.stringify(this.sendMessage));
				let socketRe = await this.$store.dispatch('websocket/WEBSOCKET_SEND', JSON.stringify(this.sendMessage));
				console.log(socketRe, 'socketRe');
			}
			// let socketRe = await this.$store.dispatch('websocket/WEBSOCKET_SEND', JSON.stringify(this.sendMessage));
			// console.log(this.messageList, 'messageList');
			// console.log(socketRe, 'socketRe');
		},

		/* 在线消息 */

		/* 离线消息 */
		quitSocket() {
			let that = this;
			console.log(that.socketTask, 'socketTask');
			that.socketTask.close();
		},

		/* socketTask */
		connectSocket() {
			let that = this;
			let token = uni.getStorageSync('token') || 'c2FiZXI6c2FiZXJfc2VjcmV0';
			that.socketTask = uni.connectSocket({
				url: `wss://api.imquanzi.com/ws?token=${token}`,
				success(res) {
					console.log('socketTask连接成功');
					that.isSuccess = true;
				},
				fail(err) {
					console.log('报错', err);
				}
			});
			that.socketTask.onOpen(function(res) {
				// let that = this;
				console.log('socketTask连接已打开！');
				that.isSuccess = true;
				// that.getStatus();
				that.heart();
			});
			that.socketTask.onMessage(function(res) {
				console.log('收到服务器内容：' + res.data);
				that.handlerMsg(JSON.parse(res.data)); //这里是对获取到的数据进行操作
			});
			that.socketTask.onError(function(res) {
				console.log('socketTask连接打开失败，请检查！');
				that.socketTask = null;
				clearInterval(that.timer);
				that.isSuccess = false;
				that.connectNum++;
				// console.log('失败重连' + that.connectNum);
				if (that.connectNum >= 6) {
					uni.showToast({
						title: '失败重连 超过6次 请重新连接websocket'
					});
					// that.isClose = false;
					return;
				} else {
					that.reconnect();
					that.connectNum = 1;
				}
				// that.connectSocket();
				//进入重新连接
			});
			// // 监听连接关闭 -
			that.socketTask.onClose(e => {
				console.log('socketTask连接关闭！');
				clearInterval(that.timer);
				that.timer = '';
				// if (!that.isClose) {
				// 	that.reconnect();
				// }
			});
			console.log(that.socketTask, 'socketTask对象');
		},
		//进入重新连接
		reconnect() {
			let that = this;
			console.log('进入断线重连');
			// this.socketTask.close();
			that.socketTask = null;
			that.connectSocket();
		},
		//发送消息
		sendSocketMessage(msg) {
			console.log('发送信息');
			var that = this;
			console.log(msg);
			console.log(that.socketTask, 'that.socketTask');
			// debugger;
			return new Promise((reslove, reject) => {
				that.socketTask.send({
					data: msg,
					success(res) {
						console.log('发送成功');
						console.log(res, '成功的数据');
						reslove(res);
					},
					fail(res) {
						console.log('发送失败');
						console.log(res);
						console.log(res, '失败的数据');
						reject(res);
					}
				});
			});
		},
		handlerMsg(data) {
			console.log(data, '处理后的数据');
			if (data.code === 10007) {
				return;
			}
			if (data.command === 11) {
				console.log(111111111);
				this.friendList.forEach(i => {
					if (i.ufriendId === data.data.from) {
						this.talkList[i.ufriendId] = data.data;
						this.latestMessage[i.ufriendId] = data.data;
					}
					// this.talkList[i.ufriendId] = data.data;
				});
			}
			if ((data.data.friends = {})) {
				return;
			}
			/* 离线消息 */
			// this.talkList.push(data.data);
		},
		//心跳
		heart() {
			let that = this;
			clearInterval(that.timer);
			that.timer = '';
			let userInfo = uni.getStorageSync('userInfo');
			// let msg = {
			// 	cmd: 19,
			// 	fromUserId: String(this.from),
			// 	userId: String(userInfo.userId),
			// 	// groupId: '群组id(此字段必须与userId一起使用,获取当前用户指定群组聊天消息),非必填',
			// 	// beginTime: '消息区间开始时间Date毫秒数double类型,非必填',
			// 	// endTime: '消息区间结束时间Date毫秒数double类型,非必填',
			// 	// offset: '分页偏移量int类型，类似Limit 0,10 中的0,非必填',
			// 	// count: '显示消息数量,类似Limit 0,10 中的10,非必填',
			// 	// type: '消息类型(0:离线消息,1:历史消息)'
			// 	type: 1
			// };
			let msg = {
				cmd: 13,
				hbbyte: '-127'
			};
			that.timer = setInterval(() => {
				that.sendSocketMessage(JSON.stringify(msg))
					.then(res => {
						// console.log('心跳成功');
					})
					.catch(res => {
						console.log('发送失败');
						console.log(res);
					});
			}, 5000);
		}
	}
};
</script>

<style lang="scss" scoped>
.scroll-view_H {
	white-space: nowrap;
	width: 100%;
}
.scroll-view-item_H {
	display: inline-block;
	width: 300rpx;
	height: 84rpx;
	line-height: 84rpx;
	text-align: center;
	font-size: 32rpx;
	background-color: #a054fe;
	border-radius: 18rpx 18rpx 18rpx 18rpx;
	margin-left: 16rpx;
}

.test {
	// padding-bottom: calc(var(--window-bottom) + 30rpx);
	padding-bottom: 162rpx;
}

.message {
	// width: 96rpx;
	// height: 66rpx;
	font-size: 48rpx;
	font-family: PingFang SC-Medium, PingFang SC;
	font-weight: 500;
	color: #1b1b1b;
	// line-height: 0rpx;
	-webkit-background-clip: text;
	// -webkit-text-fill-color: transparent;
}

.contactMen {
	// width: 144rpx;
	// height: 66rpx;
	font-size: 48rpx;
	font-family: PingFang SC-Medium, PingFang SC;
	font-weight: 500;
	color: #9f9f9f;
	// line-height: 0rpx;
	-webkit-background-clip: text;
	// -webkit-text-fill-color: transparent;
}

.myFamily {
	// width: 96rpx;
	// height: 44rpx;
	font-size: 32rpx;
	font-family: PingFang SC-Regular, PingFang SC;
	font-weight: 400;
	color: #1b1b1b;
	// line-height: 0rpx;
	-webkit-background-clip: text;
	// -webkit-text-fill-color: transparent;
}

.myMessage {
	width: 396rpx;
	// height: 32rpx;
	font-size: 22rpx;
	font-family: PingFang SC-Regular, PingFang SC;
	font-weight: 400;
	color: #d9d9d9;
	// line-height: 0rpx;
	-webkit-background-clip: text;
	// -webkit-text-fill-color: transparent;
}

.myTime {
	// width: 52rpx;
	// height: 28rpx;
	font-size: 20rpx;
	font-family: PingFang SC-Regular, PingFang SC;
	font-weight: 400;
	color: #cfd4dc;
	// line-height: 0rpx;
	-webkit-background-clip: text;
	// -webkit-text-fill-color: transparent;
}
</style>
